package com.wan.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Description: 验证码的Controller
 * date: 2021/12/23 10:28
 *
 * @author 万富
 * @since JDK 1.8
 */
@RestController
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha",produces = "image/jpeg") // 返回输出一个图片，方便接口测试
    public void capthcha(HttpServletRequest request, HttpServletResponse response){
        // 定义响应头的输出类型为image/jpeg类型
        response.setDateHeader("Expires",0);
        // http/1.1 不使用缓存
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        // IE extended no-cache headers
        response.addHeader("Cache-Control","post-check=0, pre-check=0");
        // no-cache header
        response.setHeader("Pragma","no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");

        // -------------------------生成验证码--start-----------

        String text = defaultKaptcha.createText();
        System.out.println("生成的验证码是："+text);

        // 将生成的验证码放在session中--------------------------------
        request.getSession().setAttribute("captcha",text);
        // 根据文本验证码创建图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            // 输出流输出图片
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // -------------------------生成验证码--end-------------
    }


}
